import { Base64 } from 'js-base64'
import { Format, IsNull } from '@/utils/utils'
import http from '@/utils/http'
import JSEncrypt from 'jsencrypt'
import systemService from '@/services/system-service'
import store from '@/store'
import Global from '@/utils/Global.js'

const LoginService = {
  isLogin: false,
  userInfo: null,
  loginTime: null,
  SystemName: '',
  urlString: '',

  async loginByAuthCode(code, systemCode, url, callback) {
    debugger
    try {
      const api =
                Global.addressip + '/api/Organization/LoginByAuthCode?' +
                (IsNull(systemCode) ? `code=${code}` : `systemCode=${systemCode}&code=${code}`)
      const response = await http.POST(api, `"${url}"`)
      if (response.Success && response.Result.Result) {
        this.cleanLoginInfo()
        localStorage.setItem('user-info', JSON.stringify(response.Result))
        this.setTime()
        callback(true)
      } else {
        callback(false)
      }
    } catch (error) {
      callback(false)
    }
  },

  loginByLoginCode: async function(code, callback) {
    debugger
    try {
      const response = await http.GET(Global.addressip + '/api/Organization/LoginByCode/' + code)
      if (response.Success && response.Result.Result) {
        this.cleanLoginInfo()
        localStorage.setItem('user-info', JSON.stringify(response.Result))
        this.setTime()
        callback(true)
      } else {
        callback(false)
      }
    } catch (error) {
      callback(false)
    }
  },
  /**
     * 解密快速通道key，
     * @param key
     * @param privateKey 私钥
     */
  decode: function(key, privateKey) {
    const keyDecode1 = Base64.decode(key)
    const keyArray = keyDecode1.split(privateKey)
    const timeKey = Base64.decode(keyArray[1])
    if (timeKey.length > 10) {
      const t = new Date().getTime() - 24 * 60 * 60 * 1000
      if (parseInt(timeKey) > parseInt(Format(new Date(t), 'yyyyMMddHHmmss'))) {
        return Base64.decode(keyArray[0])
      }
    }
    // 登录名 加密=> MDA2ODI1 +私钥(whdac)+时间戳  =>加密
    // const dateKey = new Date(new Date().toLocaleDateString()).getTime();
    // console.log('解密开始1:Key=' + key + ';PrivateKey=' + privateKey);
    const dateKey = Base64.encode(Format(new Date(), 'yyyyMMdd'))
    // console.log('解密开始2:dateKey=' + dateKey);
    const decode1 = Base64.decode(key)
      .replace(privateKey, '')
      .replace(dateKey, '')
    // console.log('解密开始3:decode1=' + decode1);
    const keyValue = Base64.decode(decode1)
    // console.log('解密开始4:login=' + keyValue);
    return keyValue
  },
  login: async function(code, password, isWebChatLogin = false) {
    const Pwd = await encrypt(password)
    const res = await http.POST(
      Global.addressip + '/api/Organization/Login', {
        Code: code || '',
        Pwd: Pwd
      },
      null,
      isWebChatLogin
    )

    if (res.Success && res.Result.Result) {
      this.cleanLoginInfo()
      localStorage.setItem('user-info', JSON.stringify(res.Result))

      this.setTime()
    } else {
      res.Success = false
      res.Message = res.Result.Message
    }
    return res
  },
  logout: async function(returnUrl) {
    let url =
            IsNull(this.userInfo) || IsNull(this.userInfo.LogoutUrl)
              ? '/login'
              : this.userInfo.LogoutUrl.replace(/{userId}/gi, this.userInfo.ObjectID)
    this.userLoginOut()
    this.cleanLoginInfo()
    const res = await http.GET(Global.addressip + '/api/System/GetSystemSetting')
    let urlString = false
    if (res && res.Result && res.Result.Urlstring == true) {
      urlString = true
    }
    if (!urlString) {
      returnUrl = ''
    }
    if (!IsNull(returnUrl)) {
      const urlHasQuery = url.indexOf('?') > -1
      url += `${urlHasQuery ? '&' : '?'}returnUrl=${Base64.encode(returnUrl)}`
    }
    window.location.href = url
  },
  userLoginOut() {
    http.GET(Global.addressip + '/api/Organization/LoginOut/' + this.userInfo.ObjectID)
  },
  loginbyTokenId: async function(tokenId) {
    const res = await http.LoginByToken(
      '/api/Organization/Login', {
        Code: '***',
        Pwd: '***'
      },
      tokenId
    )

    if (res.Success && res.Result.Result) {
      localStorage.setItem('user-info', JSON.stringify(res.Result))

      this.setTime()
    } else {
      res.Success = false
      res.Message = res.Result.Message
    }
    return res
  },
  /** 用户登陆是否过期 */
  isTimed: function() {
    if (!this.loginTime || !this.userInfo.ObjectID) return true
    const exp_Minute = this.userInfo.UserCacheExpMinute || 30
    return new Date().getTime() - this.loginTime > exp_Minute * 60 * 1000
  },
  setTime: function() {
    localStorage.setItem('login-time', new Date().getTime())
  },
  cleanLoginInfo() {
    localStorage.setItem('null_item', null)
    localStorage.removeItem('user-info')
    localStorage.removeItem('login-time')
  }
}

Object.defineProperty(LoginService, 'isLogin', {
  get() {
    return !!this.userInfo
  }
})

Object.defineProperty(LoginService, 'userInfo', {
  get() {
    localStorage.setItem('null_item', null)
    try {
      const user = JSON.parse(localStorage.getItem('user-info'))
      if (user)
      // user.isAdministrator =
      //     user.Code && user.Code.toLocaleLowerCase() === 'administrator';
      { user.isAdministrator = user.IsAdmin }
      return user
    } catch {
      return null
    }
  }
})

Object.defineProperty(LoginService, 'loginTime', {
  get() {
    localStorage.setItem('null_item', null)
    try {
      return localStorage.getItem('login-time')
    } catch {
      return null
    }
  }
})

async function encrypt(password = '1') {
  const { PublicKey, PasswordRsaEncrypt } = await systemService.getSystemSetting()
  if (PasswordRsaEncrypt) {
    const encrypt = new JSEncrypt()
    encrypt.setPublicKey(PublicKey)
    password = encrypt.encrypt(password)
  }
  return password
}

export default LoginService
